'use strict';
const Service = require('egg').Service;

class ConfigService extends Service {

  /*
   * 获取系统配置或者更新配置
   * @param string key 配置名称
   * @param object data 配置数据  {k1:'v1',k2:'v2'}
   * @return object or string or bool
   */
  async systemConfig(key, data = {}) {
    if (!key) return '';
    const key_param = key.split('.');
    const condition = { inc_type: key_param[0] };
    const data_keys = Object.keys(data);
    if (data_keys.length) { // 添加和编辑
      const name_list = await this.ctx.model.Config.findAll({ where: condition, attributes: [ 'name' ], raw: true });
      const fields = []; // 存储键列表
      name_list.forEach(item => {
        fields.push(item.name);
      });
      for (const key in data) {
        if (key === 'inc_type' || key === '_csrf') continue;// 过滤类型和表单验证
        condition.name = key;
        if (fields.includes(key)) {
          await this.ctx.model.Config.update({ value: data[key] }, { where: condition });
        } else {
          const insert_data = Object.assign({}, condition);
          insert_data.value = data[key];
          await this.ctx.model.Config.create(insert_data);
        }
      }
      return true;
    }
    // 查询
    if (key_param[1]) condition.name = key_param[1];
    const config_list = await this.ctx.model.Config.findAll({
      where: condition,
      attributes: [ 'name', 'value' ],
      raw: true,
    });
    const config_temp = {};
    for (const item of config_list) {
      config_temp[item.name] = item.value;
    }
    return key_param.length > 1 ? config_temp[key_param[1]] : config_temp;
  }

  // 获取短信模板
  getSmsTemplete(tpl_id = 0) {
    const tpl_list = this.config.sms_templete;
    const code = this.ctx.helper.rand(100000, 999999) || '';
    let tpl = tpl_list[tpl_id];
    if (tpl && code) tpl = tpl.replace('#code#', code);
    return { tpl, code };
  }

  /*
   * 短信发送
   * @param string mobile 手机号
   * @param string text 内容
   * return bool
   * */
  async sendSms(mobile, text) {
    const apikey = await this.systemConfig('sms.sms_apikey');
    const url = 'http://utf8.api.smschinese.cn/';
    if (this.ctx.helper.check_mobile(mobile) && apikey && text) {
      const res = await this.app.curl(url, { method: 'GET', data: { uid: 'text', key: apikey, smsMob: mobile, smsText: text } });
      console.log('短信调用结果：' + res.data);
      if (res.status == 200) {
        const content = JSON.parse(res.data);
        if (content.code == 0) {
          return true;
        }
      }
    }
    return false;
  }

  /*
   * 短信验证码验证
   * @param string mobile 手机号
   * @param string code 验证码
   * return bool
   * */
  checkSmsCode(mobile, code) {
    const send_mobile = this.ctx.session.send_mobile;
    const send_code = this.ctx.session.mobile_code;
    const send_time = this.ctx.cookies.get('code_time');
    if (parseInt(mobile) !== parseInt(send_mobile) || parseInt(code) !== parseInt(send_code)) {
      return '参数错误';
    }
    if (!send_time) {
      return '验证码已过期';
    }
    return true;
  }

}

module.exports = ConfigService;
